package com.zl.tby.icc;
import com.zl.tby.core.common.R;

/**
 * 存储icc的token
 * @author changpeng
 * @version 1.0
 * @since 2024/9/15 10:29
 */
public class IccTokenCache {
    private static IccTokenCache instance = null;

    private static IccToken loginBean = null;
    // 单位秒
    private static Long saveTime = null;

    private static synchronized void syncInit() {
        if (instance == null) {
            instance = new IccTokenCache();
        }
    }

    public static IccTokenCache getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    public synchronized IccToken getToken() {
        if (loginBean == null) {
            // 获取token
            R<IccToken> r = IccUtil.login();
            if (r.getCode() != 0) {
                return null;
            }
            saveTime = System.currentTimeMillis() / 1000;
            loginBean = r.getData();
        }
        long current = System.currentTimeMillis() / 1000;
        if ((current - saveTime.longValue()) > loginBean.getExpires_in()) {
            // token有效期是2个小时为了方便，这就限制为一个小时了
            // 获取token
            R<IccToken> r = IccUtil.login();
            if (r.getCode() != 0) {
                return null;
            }
            saveTime = r.getData().getExpires_in();
            loginBean = r.getData();
        }
        return loginBean;
    }
}
